﻿Imports System.Globalization

Public Class frmNotaRemision

    Private Sub frmNotaRemision_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dgvdetalle.AutoGenerateColumns = False
        btnImprimir.Visible = False

        cboEstado.SelectedIndex = 0

        If codNotaRemision > 0 Then
            oiml.CargarCombos(cboMotivo, "motivo", "idMotivoStock", controllerStock.get_motivos_stock_all(oiml.dbConn, False))
        Else
            oiml.CargarCombos(cboMotivo, "motivo", "idMotivoStock", controllerStock.get_motivos_stock_all(oiml.dbConn, True))
        End If

        CargarDatosDeposito(False)

        CargarNotasRemision()

    End Sub

    Private Sub CargarDatosDeposito(ByVal recarga As Boolean)

        If Not recarga Then
            oiml.CargarCombos(cboDestino, "descripcion", "idDeposito", controllerStock.get_depositos(oiml.dbConn, 0, "", "", True))
        End If


        If (cboMotivo.Text.Contains("TRANSLADO")) Then

            lblDestino.Visible = True
            cboDestino.Visible = True

            If cboDestino.SelectedValue.ToString() <> "" Then
                oiml.CargarCombos(cboDeposito, "descripcion", "idDeposito", controllerStock.get_depositos_NonDestino(oiml.dbConn, cboDestino.SelectedValue))
            End If

        Else
            lblDestino.Visible = False
            cboDestino.Visible = False

            oiml.CargarCombos(cboDeposito, "descripcion", "idDeposito", controllerStock.get_depositos(oiml.dbConn, 0, "", "", True))
        End If

    End Sub

    Dim controller As New ControllerSigeco.controller_compras
    Dim controllerStock As New ControllerSigeco.controller_stock

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private _codNotaRemision As Integer = 0

    Public Property codNotaRemision() As Integer
        Get
            Return _codNotaRemision
        End Get
        Set(ByVal value As Integer)
            _codNotaRemision = value
        End Set
    End Property

    Private _codProveedor As Integer = 0

    Public Property codProveedor() As Integer
        Get
            Return _codProveedor
        End Get
        Set(ByVal value As Integer)
            _codProveedor = value
        End Set
    End Property

    Private _codCliente As Integer = 0

    Public Property codCliente() As Integer
        Get
            Return _codCliente
        End Get
        Set(ByVal value As Integer)
            _codCliente = value
        End Set
    End Property

    Private _codMercaderia As Integer = 0

    Public Property codMercaderia() As Integer
        Get
            Return _codMercaderia
        End Get
        Set(ByVal value As Integer)
            _codMercaderia = value
        End Set
    End Property

    Private _codMercaderiaLote As Integer = 0

    Public Property codMercaderiaLote() As Integer
        Get
            Return _codMercaderiaLote
        End Get
        Set(ByVal value As Integer)
            _codMercaderiaLote = value
        End Set
    End Property

    Private _codMercaderiaDetalle As Integer = 0

    Public Property codMercaderiaDetalle() As Integer
        Get
            Return _codMercaderiaDetalle
        End Get
        Set(ByVal value As Integer)
            _codMercaderiaDetalle = value
        End Set
    End Property

    Private _codCompra As Integer = 0

    Public Property codCompra() As Integer
        Get
            Return _codCompra
        End Get
        Set(ByVal value As Integer)
            _codCompra = value
        End Set
    End Property

    Private _codVenta As Integer = 0

    Public Property codVenta() As Integer
        Get
            Return _codVenta
        End Get
        Set(ByVal value As Integer)
            _codVenta = value
        End Set
    End Property

    Private _vistaVenta As Boolean = False

    Public Property vistaVenta() As Boolean
        Get
            Return _vistaVenta
        End Get
        Set(ByVal value As Boolean)
            _vistaVenta = value
        End Set
    End Property

    Private m_frmBusMercaderia As frmMercaderiaBuscador
    Public Property frmBusMercaderia() As frmMercaderiaBuscador
        Get
            Return m_frmBusMercaderia
        End Get
        Set(ByVal value As frmMercaderiaBuscador)
            m_frmBusMercaderia = value
        End Set
    End Property

    Private m_frmBusProveedor As frmProveedorBuscador
    Public Property frmBusProveedor() As frmProveedorBuscador
        Get
            Return m_frmBusProveedor
        End Get
        Set(ByVal value As frmProveedorBuscador)
            m_frmBusProveedor = value
        End Set
    End Property

    Private Sub btnBuscProveedor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscProveedor.Click

        frmBusProveedor = New frmProveedorBuscador
        frmBusProveedor.ShowDialog()
        txtProveedor.Text = frmBusProveedor.ProveedorDesc
        codProveedor = frmBusProveedor.codProveedor

        If codProveedor > 0 Then
            btnBuscMercaderia.Focus()
        End If

    End Sub

    Private Sub btnBuscMercaderia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscMercaderia.Click

        frmBusMercaderia = New frmMercaderiaBuscador

        If (cboMotivo.Text.Contains("TRANSLADO")) Then
            frmBusMercaderia.codDeposito = cboDeposito.SelectedValue
            frmBusMercaderia.esVenta = True
        Else
            frmBusMercaderia.codDeposito = 0
            frmBusMercaderia.esVenta = False
        End If

        frmBusMercaderia.ShowDialog()
        txtMercaderia.Text = frmBusMercaderia.MercaderiaDesc
        codMercaderia = frmBusMercaderia.codMercaderia
        codMercaderiaLote = frmBusMercaderia.codMercaderiaLote

        If codMercaderia > 0 Then
            txtcantidad.Focus()
        End If

    End Sub

    Private Sub txtcantidad_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.Leave
        If IsNumeric(txtcantidad.Text) Then

        End If
    End Sub

    Private Sub CargarNotasRemisionDetalle()
        Try

            codMercaderia = 0
            codMercaderiaDetalle = 0
            txtMercaderia.Text = ""
            txtLote.Text = ""
            cbxVto.Checked = False
            txtcantidad.Text = 1

            Dim ds As New DataTable
            ds = controller.get_NotasRemision_Detalles_All(oiml.dbConn, codNotaRemision)

            If Not ds Is Nothing Then

                dgvdetalle.DataSource = ds

                If (cboMotivo.Text.Contains("TRANSLADO")) Then
                    cboDeposito.Enabled = False
                    cboMotivo.Enabled = False
                    cboDestino.Enabled = False
                End If

            Else

                dgvdetalle.DataSource = Nothing
                cboDeposito.Enabled = True
                cboMotivo.Enabled = True
                cboDestino.Enabled = True

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Dim ci As CultureInfo

    Private Sub CargarNotasRemision()
        Try
            If codNotaRemision > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Remision_ByID(oiml.dbConn, codNotaRemision)

                If Not ds Is Nothing Then

                    txtActualizadoFecha.Text = ds.Rows(0)("actualizadoFecha_")
                    txtActualizadoPor.Text = ds.Rows(0)("usuario")

                    If Not ds.Rows(0)("nroCompra") Is DBNull.Value Then
                        codCompra = ds.Rows(0)("idCompra")
                        txtCompra.Text = ds.Rows(0)("nroCompra")
                    End If

                    If Not ds.Rows(0)("idDepositoDestino") Is DBNull.Value Then
                        cboDestino.SelectedValue = ds.Rows(0)("idDepositoDestino")
                        CargarDatosDeposito(True)

                        If Not ds.Rows(0)("idDepositoOrigen") Is DBNull.Value Then
                            cboDeposito.SelectedValue = ds.Rows(0)("idDepositoOrigen")
                        End If
                    End If

                    If Not ds.Rows(0)("nroVenta") Is DBNull.Value Then
                        codVenta = ds.Rows(0)("idVenta")
                        txtCompra.Text = ds.Rows(0)("nroVenta")
                        grpDetalle.Visible = False
                    End If

                    btnVer.Visible = Not vistaVenta

                    If ds.Rows(0)("idCliente").ToString() <> "" Then

                        txtProveedor.Text = ds.Rows(0)("cliente")
                        codCliente = ds.Rows(0)("idCliente")

                    Else

                        txtProveedor.Text = ds.Rows(0)("proveedor")
                        codProveedor = ds.Rows(0)("idProveedor")

                    End If

                    nroRemision.Text = ds.Rows(0)("nroComprobante")
                    fechaFactura.Value = ds.Rows(0)("fecha")
                    cboEstado.Text = ds.Rows(0)("estado")
                    ControlEstados()

                    cboMotivo.SelectedValue = ds.Rows(0)("idMotivoStock")

                    If (cboMotivo.Text.Contains("TRANSLADO") And ds.Rows(0)("nroRecepcion").ToString = "" And ds.Rows(0)("estado") = "APROBADA") Then
                        btnRecepcion.Visible = True
                    Else
                        btnRecepcion.Visible = False
                    End If

                    CargarNotasRemisionDetalle()

                End If

            Else

                btnRecepcion.Visible = False
                cboEstado.Text = "EN PROCESO"
                nroRemision.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstados()

        If cboEstado.Text = "APROBADA" Then

            nroRemision.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboMotivo.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            btnVer.Enabled = False
            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False

            btnEliminar.Enabled = False
            btnEliminarDetalle.Enabled = False

            btnConfirmar.Visible = False
            txtLote.Enabled = False
            cbxVto.Enabled = False
            cbxVto.Checked = False
            cboDeposito.Enabled = False

            txtcantidad.Enabled = False

            btnCancelar.Focus()

        ElseIf cboEstado.Text = "ANULADA" Then

            nroRemision.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboMotivo.Enabled = False
            btnVer.Enabled = False
            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False
            btnEliminarDetalle.Enabled = False

            btnConfirmar.Enabled = False
            txtLote.Enabled = False
            cbxVto.Enabled = False
            cbxVto.Checked = False
            cboDeposito.Enabled = False

            btnEliminar.Enabled = False
            btnAnular.Enabled = False

            txtcantidad.Enabled = False

            btnCancelar.Focus()

        End If

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        If nroRemision.Text = "" Then
            ErrorProvider1.SetError(nroRemision, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(nroRemision, "")
        End If        '

        If txtProveedor.Text = "" Or codProveedor = 0 Then
            ErrorProvider1.SetError(txtProveedor, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtProveedor, "")
        End If        '

        Return controlCampos

    End Function

    Private Function ValidarCamposDetalle() As Boolean

        Dim controlCampos As Boolean = False

        If txtMercaderia.Text = "" Then
            ErrorProvider1.SetError(txtMercaderia, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtMercaderia, "")
        End If        '

        If txtcantidad.Text = "" Or Not IsNumeric(txtcantidad.Text) Then
            ErrorProvider1.SetError(txtcantidad, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtcantidad, "")
        End If        '

        'If txtprecio.Text = "" Or Not IsNumeric(txtprecio.Text) Then
        '    ErrorProvider1.SetError(txtprecio, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider1.SetError(txtprecio, "")
        'End If        '

        Return controlCampos

    End Function

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click
        If codNotaRemision > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Remisiones", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Remision(oiml.dbConn, codNotaRemision, oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        Dim idOrigen As Integer = 0
        Dim idDestino As Integer = 0

        If (cboMotivo.Text.Contains("TRANSLADO")) Then
            idOrigen = cboDeposito.SelectedValue
            idDestino = cboDestino.SelectedValue
        End If

        If codNotaRemision = 0 Then
            codNotaRemision = controller.Insert_Remision(oiml.dbConn, nroRemision.Text, fechaFactura.Value, 0, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, idOrigen, idDestino)

            If codNotaRemision > 0 Then

                CargarNotasRemision()
                MessageBox.Show("Registro grabado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Remision(oiml.dbConn, codNotaRemision, nroRemision.Text, fechaFactura.Value, 0, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, idOrigen, idDestino) Then

                CargarNotasRemision()
                MessageBox.Show("Registro grabado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)


            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub dgvdetalle_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyDown
        If e.KeyCode = Keys.Enter Then
            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If
        End If
    End Sub

    Private Sub dgvdetalle_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then

            codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

        End If
    End Sub

    Private Sub dgvdetalle_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellClick
        Try

            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click

        If codMercaderiaDetalle > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Remisiones", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_NotasRemision_Detalle(oiml.dbConn, codMercaderiaDetalle, oiml.idUsuario, codNotaRemision, cboMotivo.SelectedValue) Then
                    CargarNotasRemision()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click

        If ValidarCamposDetalle() Then
            Exit Sub
        End If

        Dim vtoLote As String = ""
        If cbxVto.Checked Then
            vtoLote = fechaVto.Value
        End If

        Dim idOrigen As Integer = 0
        Dim idDestino As Integer = 0

        If (cboMotivo.Text.Contains("TRANSLADO")) Then
            idOrigen = cboDeposito.SelectedValue
            idDestino = cboDestino.SelectedValue
        End If

        If codNotaRemision = 0 Then

            codNotaRemision = controller.Insert_Remision(oiml.dbConn, nroRemision.Text, fechaFactura.Value, 0, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, idOrigen, idDestino)

        Else

            If controller.Update_Remision(oiml.dbConn, codNotaRemision, nroRemision.Text, fechaFactura.Value, 0, codCompra, Integer.Parse(cboMotivo.SelectedValue), cboEstado.Text, oiml.idUsuario, codCliente, codProveedor, idOrigen, idDestino) Then

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

        If codNotaRemision > 0 And codMercaderia > 0 Then

            If controller.Insert_NotasRemision_Detalle(oiml.dbConn, codNotaRemision, codMercaderia, _
                                                       Integer.Parse(txtcantidad.Text), txtLote.Text, vtoLote, _
                                                       cboDeposito.SelectedValue, cboMotivo.SelectedValue, codMercaderiaLote, 0, 0) Then
                CargarNotasRemision()
                MessageBox.Show("Registro grabado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    'Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
    '    If codCompra > 0 Then
    '        If MessageBox.Show("Desea anular el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

    '            If controller.Update_Compras_Estado(oiml.dbConn, codCompra, "ANULADA", oiml.idUsuario) Then
    '                Me.Close()

    '            Else
    '                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

    '            End If

    '        End If
    '    End If
    'End Sub

    Private Sub cbxVto_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxVto.CheckedChanged
        fechaVto.Enabled = cbxVto.Checked
    End Sub

    Private Sub btnVer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVer.Click
        If codCompra > 0 Then
            Dim compra As New frmCompras
            compra.codCompra = codCompra
            compra.soloLectura = True
            compra.ShowDialog()
        End If

        If codVenta > 0 Then
            Dim compra As New frmVentas
            compra.codVenta = codVenta
            compra.vistaVenta = True
            compra.ShowDialog()
        End If

    End Sub

    Private Sub btnBuscOrdenCompra_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub btnConfirmar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmar.Click
        If codNotaRemision > 0 Then

            If controller.Update_Remisiones_Estado(oiml.dbConn, codNotaRemision, "APROBADA", oiml.idUsuario, nroRemision.Text) Then
                CargarNotasRemision()
                MessageBox.Show("Registro confirmado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub cboMotivo_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboMotivo.SelectedValueChanged
        CargarDatosDeposito(True)
    End Sub

    Private Sub cboDestino_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboDestino.SelectedValueChanged
        CargarDatosDeposito(True)
    End Sub

    Private Sub btnRecepcion_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecepcion.Click

        If codNotaRemision > 0 Then

            If controller.Insert_Remision_Recepcion_Transaldo(oiml.dbConn, codNotaRemision, DateTime.Now, oiml.idMotivoRecepcion, oiml.idUsuario) Then
                CargarNotasRemision()
                MessageBox.Show("Translado recepcionado con exito!", "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Remisiones", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

End Class